package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleCommentDto;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.mess.ArticleVisitStreamMess;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vo.ArticleCommentVo;
import com.heima.model.article.vo.ArticleStatisticsVo;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.WmNewsCommentDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thread.AppThreadLocalUtil;
import thread.WmThreadLocalUtil;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper configMapper;
    @Autowired
    private ApArticleContentService articleContentService;

    private final static int MAX_PAGE_SIZE = 50;

    @Override
    public ResponseResult loadArticleList(short type, ArticleHomeDto articleHomeDto) {
        //获取分页数据与频道id
        Integer size = articleHomeDto.getSize();
        String tag = articleHomeDto.getTag();
        //dto参数校验
        if (size == null || size == 0) {
            size = 10;
        }
        //如果size过大,只给显示50条
        size = Math.min(size, MAX_PAGE_SIZE);
        articleHomeDto.setSize(size);
        //频道校验
        if (StringUtils.isBlank(tag)) {
            articleHomeDto.setTag(ArticleConstants.DEFAULT_TAG);
        }
//        //时间校验
//        if (articleHomeDto.getMaxBehotTime()==null)articleHomeDto.setMaxBehotTime(new Date());
//        if (articleHomeDto.getMinBehotTime()==null)articleHomeDto.setMinBehotTime(new Date());
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(type, articleHomeDto);
        return ResponseResult.okResult(apArticles);
    }

    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;

    /**
     * 保存文章到app端
     *
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
        //检查参数
        if (articleDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存文章;
        //将dto中相同属性直接拷贝到aparticle
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
        //判断文章是否存在id,修改,添加
        if (articleDto.getId() == null) {
            //id不存在,添加文章到数据库
            save(apArticle);
            //保存配置
            ApArticleConfig articleConfig = new ApArticleConfig(apArticle.getId());
            configMapper.insert(articleConfig);
            //保存文章内容
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setArticleId(apArticle.getId());
            articleContent.setContent(articleDto.getContent());
            articleContentService.save(articleContent);
        } else {
            //存在文章id,修改文章
            updateById(apArticle);
            //修改内容
            LambdaUpdateWrapper<ApArticleContent> lqw = new LambdaUpdateWrapper<>();
            lqw.eq(ApArticleContent::getArticleId, apArticle.getId());
            lqw.set(ApArticleContent::getContent, articleDto.getContent());
            articleContentService.update(lqw);
        }
        //生成静态页面上传到minio
        articleFreemarkerService.buildArticleToMinIO(apArticle, articleDto.getContent());
        return ResponseResult.okResult(apArticle.getId());
    }


    @Autowired
    private CacheService cacheService;

    /**
     * 回显文章信息
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load_article_behavior(ArticleInfoDto dto) {
        //检查参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前登录用户
        ApUser apUser = AppThreadLocalUtil.getApUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Map<String, Object> map = new HashMap<>();
        //从redis获取文章状态  点赞  不喜欢 关注 收藏
        //点赞
        String islike = (String) cacheService.hGet("BEHAVIORLIKES_" + dto.getArticleId(), apUser.getId().toString());
        if (StringUtils.isNotBlank(islike)) {
            map.put("islike", true);
        }
        //不喜欢
        String isunlike = (String) cacheService.hGet("BEHAVIORUNLIKES_" + dto.getArticleId(), apUser.getId().toString());
        if (StringUtils.isNotBlank(isunlike)) {
            map.put("isunlike", true);
        }
        //关注
        String isfollow = (String) cacheService.hGet("USERFOLLOW_" + apUser.getId(), dto.getAuthorId().toString());
        if (StringUtils.isNotBlank(isfollow)) {
            map.put("isfollow", true);
        }
        //收藏
        String iscollection = (String) cacheService.hGet("COLLECTIONBEHAVIOR_" + apUser.getId(), dto.getArticleId().toString());
        if (StringUtils.isNotBlank(iscollection)) {
            map.put("iscollection", true);
        }
        return ResponseResult.okResult(map);
    }

    /**
     * 加载文章列表
     *
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true  是首页  flase 非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        if (firstPage) {
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(jsonStr)) {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        return loadArticleList(type, dto);
    }


    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     *
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //获取之前的分值
        Long articleId = mess.getArticleId();
        Integer oldScore = computeScore(getById(articleId));
        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //2.计算文章的分值
        //计算今天的分值
        Integer todayScore = computeTodayScore(mess);
        Integer score = oldScore + todayScore;
        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

    /**
     * 评论 文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult find_news_comments(ArticleCommentDto dto) {
        Integer currentPage = dto.getPage();
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        List<ArticleCommentVo> list = apArticleMapper.findNewsComments(dto);
        int count = apArticleMapper.findNewsCommentsCount(dto);

        PageResponseResult responseResult = new PageResponseResult(currentPage, dto.getSize(), count);
        responseResult.setData(list);
        return responseResult;
    }


    /**
     * 图文统计
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult newsDimension(WmNewsPageReqDto dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //数据处理
        Integer authorId = dto.getAuthorId();
        LambdaQueryWrapper<ApArticle> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ApArticle::getAuthorId, authorId)
                .between(ApArticle::getPublishTime, dto.getBeginDate(), dto.getEndDate());

        List<ApArticle> apArticleList = list(lqw);

        if (apArticleList == null || apArticleList.size() == 0) {
            return ResponseResult.okResult("暂无发布文章");
        }
        ArticleStatisticsVo vo = new ArticleStatisticsVo();
        //图文发布量
        vo.setPublishNum(apArticleList.size());
        //点赞和收藏
        int likesNum = apArticleList.stream().filter(apArticle -> apArticle.getLikes() != null).mapToInt(ApArticle::getLikes).sum();
        int collectNum = apArticleList.stream().filter(apArticle -> apArticle.getCollection() != null).mapToInt(ApArticle::getCollection).sum();
        vo.setLikesNum(likesNum);
        vo.setCollectNum(collectNum);
        return ResponseResult.okResult(vo);
    }


    /**
     * 发布详情统计
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult newsPage(WmNewsPageReqDto dto) {
        LambdaQueryWrapper<ApArticle> lqw = new LambdaQueryWrapper<>();
        Page<ApArticle> page = new Page<>(dto.getPage(), dto.getSize());
        lqw.eq(ApArticle::getAuthorId, dto.getAuthorId())
                .between(ApArticle::getPublishTime, dto.getBeginDate(), dto.getEndDate());
        page = page(page, lqw);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 单篇文章分析
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult newsDetail(WmNewsPageReqDto dto) {
        return ResponseResult.okResult("");
    }

    @Override
    public void reduceComment(Long articleId) {
        ApArticle apArticle = getById(articleId);
        apArticle.setComment(apArticle.getComment() - 1);
    }

    /**
     * 计算今天的分值
     *
     * @param mess
     * @return
     */
    private Integer computeTodayScore(ArticleVisitStreamMess mess) {
        int score = 0;
        int view = mess.getView();
        int like = mess.getLike();
        int comment = mess.getComment();
        int collect = mess.getCollect();
        score += like * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        score += view;
        score += comment * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        score += collect * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        return score * 3;
    }

    /**
     * 替换数据并且存入到redis
     *
     * @param apArticle
     * @param score
     * @param key
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String key) {
        String articleListStr = cacheService.get(key);
        if (StringUtils.isNotBlank(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);

            boolean flag = true;

            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }

            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }


                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(key, JSON.toJSONString(hotArticleVoList));

        }
    }

    /**
     * 更新文章行为数量
     *
     * @param mess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection() == null ? mess.getCollect() : apArticle.getCollection() + mess.getCollect());
        apArticle.setComment(apArticle.getComment() == null ? mess.getComment() : apArticle.getComment() + mess.getComment());
        apArticle.setLikes(apArticle.getLikes() == null ? mess.getLike() : apArticle.getLikes() + mess.getLike());
        apArticle.setViews(apArticle.getViews() == null ? mess.getView() : apArticle.getViews() + mess.getView());
        updateById(apArticle);
        return apArticle;

    }

    /**
     * 计算文章的具体分值
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
